import {Component} from 'react'
import {View, ScrollView, Text} from '@tarojs/components'
import {observer, inject} from 'mobx-react'
import {toJS} from "mobx"

import './index.scss'
import {toast, router} from "../../utils";
import { AtAvatar, AtList, AtListItem } from "taro-ui"

@inject('store')
@observer
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      refresherTriggered: false
    }
  }
  componentDidMount() {
    this.queryData()
  }

  queryData = (bool) => {
    return this.props.store.appStore.getRecSongList(bool)
  }

  onSearch = () => {
    router.push('/pages/search/index',)
  }

  onScrollToUpper = () => {

  }

  onScrollToLower = () => {
    this.queryData()
  }

  onRefresherPulling = () => {
    if(this.state.refresherTriggered)return;
    this.timer && clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      this.setState({
        refresherTriggered: true
      })
    }, 300)
  }

  onRefresherRefresh = () => {
   this.queryData(true, ).finally(() => {
     setTimeout(() => {
       this.onRefresherRestore();
     },500)
   })

  }

  onRefresherRestore = () => {
    this.setState({
      refresherTriggered: false
    })
  }

  render() {
    const {
      appStore: {recSongList}
    } = this.props.store;
    return (
      <ScrollView
        scrollY
        scrollWithAnimation
        scrollTop={0}
        style={{height: '100vh'}}
        lowerThreshold={0}
        upperThreshold={0}
        refresherEnabled={true}
        refresherTriggered={this.state.refresherTriggered}
        onScrollToUpper={this.onScrollToUpper}
        onScrollToLower={this.onScrollToLower}
        onRefresherPulling={this.onRefresherPulling}
        onRefresherRefresh={this.onRefresherRefresh}
        onRefresherRestore={this.onRefresherRestore}
      >
        <View className='index page'>
          <View className="search-view" onClick={this.onSearch}><Text>搜索歌曲</Text></View>
          <AtList style={{border: 'none'}}>
            {
              recSongList.map(item => (
                <AtListItem
                  title={item.name}
                  note={item.song.artists.map(aitem => aitem.name).join('/') + ' - ' + item.song.album.company}
                  arrow={false}
                  thumb={item.picUrl}
                  hasBorder={false}
                />
              ))
            }
          </AtList>

        </View>
      </ScrollView>

    )
  }
}

export default Index
